<template>
  <div class="task-card" shadow="hover">
    <el-row class="task-card-main" type="flex" justify="space-between">
      <el-row class="task-card-content">
        <div class="task-card-inforn"> 
          <el-tooltip class="item" effect="dark" :content="getCardNameLabel(card)" :disabled="!isCardNameOverflow" placement="top-start"><h2 class="task-card-name" ref="parentNameWidth"><span ref="childNameWidth">{{getCardNameLabel(card)}}</span></h2> </el-tooltip>                                   
          <el-tooltip class="item" effect="dark" :content="getDesLabel(card)" :disabled="!isOverflow" placement="top"><p class="task-card-des" ref="parentHeight"><span ref="childHeight">{{htmlUnEscape(getDesLabel(card))}}</span></p></el-tooltip>
          <div class="task-card-others">
            <div class="task-card-scope">
              <p>  
                <span class="task-card-tit">{{$t('event.setting.additional.component.cardItem.label1')}}：</span>
                <el-dropdown placement="top" @command="modifyTaskType">
                  <span v-if="rangeName.length>30">{{$t('event.setting.additional.component.cardItem.des1', {data1: rangeName.substring(0, 30), data2: card.range.length})}}</span>
                  <span v-else>{{rangeName}}</span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item v-for="(item,index) in card.range" :key="index" :command="item.id">{{item.name}}</el-dropdown-item>       
                  </el-dropdown-menu>
                </el-dropdown>
              </p>
            </div>
            <div class="task-card-li">
              <p>{{$t('common.base.type')}}：<span class="task_type">{{card.inputType=='single'?$t('common.base.onceTime'):$t('common.base.moreTime')}}</span></p>
              <p>{{$t('event.setting.additional.component.cardItem.label2')}}：<span class="task_see" @click="onSee">{{$t('common.base.view')}}</span></p>
            </div>
          </div>
        </div>
      </el-row>
      <div class="task-card-switch">
        <el-switch v-model="card.enabled" :active-value="1" :inactive-value="0" @change="statusChange(card.enabled)"/>
      </div>
    </el-row>
    <!-- start 操作 -->
    <el-row class="task-card-opearte" type="flex">
      <div class="task-card-opearte-more" >
        <el-dropdown placement="top" v-if="!card.config||(card.config&&!card.config.notEdit)">
          <i class="icon-diandiandian iconfont">{{$t('common.base.moreOperator')}}</i>
          <el-dropdown-menu slot="dropdown">
            <!-- 系统附加组件不能修改名称 -->
            <el-dropdown-item v-if="!card.specialfrom || !card.isSystem">
              <div class="opearte_btn" @click="editRename"><i class="iconfont icon-edit-square"></i>{{$t('common.base.rename')}}</div>
            </el-dropdown-item>
            <el-dropdown-item>
              <div class="opearte_btn" @click="delTaskCard"><i class="iconfont icon-delete"></i>{{$t('common.base.delete')}}</div>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <div class="task-card-opearte-modify" @click="modifyTaskForm">
        <i class="icon-edit-square iconfont">{{$t('common.base.edit')}}</i>
      </div>
    </el-row>
    <!-- end 操作 -->

    <!-- 添加编辑附加组件 -->
    <edit-cardname-dialog :id="card.id" ref="batchCardnameDialog" @editCardSubmit="editCardSubmit"></edit-cardname-dialog>

    <!-- 统计 -->
    <statistical-dialog :card="card" ref="statisteDialog" ></statistical-dialog>

    <!-- 备件服务清单统计 -->
    <spare-statistics-dialog :card="card" ref="spareStatisteDialog" ></spare-statistics-dialog>

  </div>
</template>

<script>
import * as SettingTaskApi from '@src/api/SettingTaskApi';

import EditCardnameDialog from '../components/EditCardnameDialog';
import statisticalDialog from '../components/statisticalDialog';
import SpareStatisticDialog from '../components/SpareStatisticDialog';
import { openAccurateTab } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { CardNameLabelEnum } from '@model/enum/LabelEnum'
export default {
  name: 'task-card-item',
  props: {
    card:{
      type: Object,
      default: () => ({})
    }
  },
  computed:{
    rangeName() {   
      let range = this.card.range.map((item)=> {
        return item.name     
      }).join('，')
      return range
    }
  },
  data() {
    return {
      isCardNameOverflow: false,
      isOverflow: false
    }
  },
  mounted() {
    this.initOverflow()
  },
  methods: {
    // 获取附加组件标题的多语言label
    getCardNameLabel(item) {
      const { name, cardNameLanguage } = item
      const locale = this.$i18n.locale
      return cardNameLanguage?.locale || CardNameLabelEnum[name] || name
    },
    getDesLabel(item){
      const { description, descriptionLanguage } = item
      const locale = this.$i18n.locale
      const des_ =  descriptionLanguage?.locale || description
      return this.htmlUnEscape(des_)
    },
    // 初始化溢出tips
    initOverflow() {
      this.$nextTick(()=> {
        this.isCardNameOverflow = this.$refs?.parentNameWidth?.offsetWidth < this.$refs?.childNameWidth?.offsetWidth
        this.isOverflow = this.$refs?.parentHeight?.offsetWidth < this.$refs?.childHeight?.offsetWidth
      })
    },
    editCardSubmit() {
      location.reload();
    },
    // 删除组件
    delTaskCard() {
      this.$confirm(this.$t('customer.setting.customerCardItem.tips1', {data1: this.card.name, data2: this.$t('common.task.taskType')}), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.makeSure'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning',
      }).then(() => {
        SettingTaskApi.onDeleteCard({id: this.card.id}).then(res=>{
          const { code, message, result } = res;
          if(code == 0){
            this.$message.success(this.$t('common.base.deleteSuccess'));
            location.reload()
          }else{
            this.$message.error(message);
          }
        }).catch(error=>{
          console.log(error)
        })
      });
    },

    // 禁用/开启附加组件
    statusChange(state) {
      let enabled = state ? 1 : 0;
      SettingTaskApi.onCardChange({id:this.card.id, enabled}).then(res=>{
        const { status, message, data } = res;
        if(status == 0){
          this.$message.success(this.$t('common.base.tip.operationSuccess'));
        }else{
          this.$message.error(message);
        }
      }).catch(error=>{
        console.log(error)
      })
    },
    // 重命名
    editRename() {
      this.$refs.batchCardnameDialog.openDialog();
    },
    // TODO:进入工单详情
    modifyTaskType(id) {
      let taskTypeId = id;
      // this.$platform.openTab({
      //   id: 'task_flow_setting',
      //   title: '工单流程设置',
      //   url: `/setting/task/taskFormSet?taskTypeId=${taskTypeId}`,
      //   reload: true,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageTaskFlowSetting,
        titleKey: this.$t('task.setting.taskFlowSettings'),
        params: `taskTypeId=${taskTypeId}`,
        reload: true,
      })
    },

    // TODO:编辑表单
    modifyTaskForm() {
      let cardId = this.card.id;
      let fromId = window.frameElement.getAttribute('id');
      if(this.card.specialfrom == '工时记录'){
        // this.$platform.openTab({
        //   id: 'task_cardhours_setting',
        //   title: '附加组件设置',
        //   url: `/setting/task/cardHoursRecord?cardId=${cardId}`,
        //   reload: true,
        //   close: true,
        //   fromId
        // });
        openAccurateTab({
          type: PageRoutesTypeEnum.PageTaskCardhoursSetting,
          params: `cardId=${cardId}`,
          reload: true,
          fromId
        })
      }else if(this.card.specialfrom == '备件清单' || this.card.specialfrom == '服务清单'){
        // this.$platform.openTab({
        //   id: 'task_cardhours_setting',
        //   title: '附加组件设置',
        //   url: `/setting/task/cardSpareService?cardId=${cardId}`,
        //   reload: true,
        //   close: true,
        //   fromId
        // });
        openAccurateTab({
          type: PageRoutesTypeEnum.PageTaskSparepartSetting,
          titleKey: this.$t('task.setting.additionalSettings'),
          params: `cardId=${cardId}`,
          reload: true,
          fromId
        })
      } else if(this.card.specialfrom == '物料申领') {
        // this.$platform.openTab({
        //   id: 'task_cardhours_setting',
        //   title: '物料申领设置',
        //   url: `/setting/task/cardMaterialApplyService?cardId=${cardId}`,
        //   reload: true,
        //   close: true,
        //   fromId
        // });
        openAccurateTab({
          type: PageRoutesTypeEnum.PageCardMaterialApplyService,
          params: `cardId=${cardId}`,
          reload: true,
          fromId
        })
      } else if(this.card.specialfrom == '故障清单') {
        openAccurateTab({
          type: PageRoutesTypeEnum.PageCardFaultListSettings,
          params: `cardId=${cardId}`,
          reload: true,
          fromId
        })
      }else{
        // this.$platform.openTab({
        //   id: 'task_card_setting',
        //   title: '附加组件表单设置',
        //   close: true,
        //   reload: true,
        //   url: `/setting/task/cardFormfields?cardId=${cardId}`,
        //   fromId
        // });
        openAccurateTab({
          type: PageRoutesTypeEnum.PageTaskCardSetting,
          params: `cardId=${cardId}`,
          reload: true,
          fromId
        })
      }
    
    },
    // TODO:查看统计
    onSee() {
      const inventoryNameMap = {
        [this.$t('task.detail.components.sparePartList')]: 'sparePartInventory',
        [this.$t('task.detail.components.serviceList')]: 'serveInventory',
        [this.$t('task.detail.components.materialApply')]: 'MATERIALS_INVENTORY'
      }
      /**
       * 因为 inventoryNameMap 这个对象里面的 key 进行了国际化的处理。
       * specialfrom 这个字段，后端没有做国际化处理。
       * 导致的问题：就是如果是中文，下面的逻辑能进去，其他语言的时候，逻辑就进不去了。
       * name字段 暂时我改动的时候，name 是和 specialfrom 的值一样，且name做了国际化处理。
       * 故更改下面的逻辑： 把 this.card.specialfrom 改为 this.card.name
       * */
      if(inventoryNameMap[this.card.name]){
        /**
         * this.$refs.spareStatisteDialog.openDialog()
         * 
         * let inventoryTypeEnum = inventoryNameMap[this.card.name]
         * this.$refs.spareStatisteDialog.form.inventoryTypeEnum = inventoryTypeEnum;  
         * 
         * 我更改的时候，以前的逻辑如上面所示，先打开了弹窗，后赋值。
         * 就导致弹窗刚打开就调接口时，会有获取不到 inventoryTypeEnum 值的时候。
         * 导致后端接口 api/task/outside/pc/inventory/countInventoryByTask 报错。
         * 所以我更改了下顺序。
         */

        let inventoryTypeEnum = inventoryNameMap[this.card.name]
        this.$refs.spareStatisteDialog.form.inventoryTypeEnum = inventoryTypeEnum;  
        this.$refs.spareStatisteDialog.openDialog()
      }else{
        this.$refs.statisteDialog.openDialog();
      }
      
      this.$track.clickStat(this.$track.formatParams('EXIST_COMP_CHECK', this.card.name))
    },
    updateTeamList(teamList){
      this.$emit('update:card', {
        ...this.card,
        teamList
      })
    },
    htmlUnEscape(value){
      if(!value) return '';
      return value.replace( /&lt;/g, '<').replace(/&gt;/g, '>');
    }
  },
  components: {
    [EditCardnameDialog.name]: EditCardnameDialog,
    [statisticalDialog.name]: statisticalDialog,
    [SpareStatisticDialog.name]: SpareStatisticDialog  
  }
}
</script>

<style lang="scss">
.task-card{
    // width: 358px;
    height: 178px;
    background: #FFFFFF;
    border-radius: 4px;
    box-shadow: 0px 4px 10px 0px rgba(0, 0, 0, 0.04); 
    &:hover{
        box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.12);
    }
    .task-card-main{
      position: relative;
        display: flex;
        height: calc(100% - 32px);
        padding: 16px 20px;
        .switch-button {
          position: absolute;
          top: 10px;
          right: 16px;
          z-index: 2;
        }
        .task-card-content{
            flex-direction: column;
            justify-content: space-between;
            height: 100%;
            width: calc(100% - 40px);
            .task-card-inforn{

                .task-card-name{  
                    margin-bottom: 0;
                    @include text-ellipsis;
                    padding-right: 32px;
                    font-size: 16px;
                    color: #333333;
                    line-height: 22px;

                }
                .task-card-des{
                    height: 17px;
                    font-size: 12px; 
                    color: #666666;
                    line-height: 17px;
                    @include text-ellipsis; 
                    margin-block-end: 0em;
                    margin-bottom: 8px;
                    margin-top: 8px;
                    // width: 248px;


                }
            }

            .task-card-others{
              margin-top: 12px;
                p{
                    margin-bottom: 4px;
                    font-size: 12px;
                    color: #666666;
                    span{
                        color: $color-primary;
                    }
                    &:last-child{
                        margin-bottom: 0;
                    }
                }
                .task-card-scope{
                    display: flex;
                    justify-content: flex-start;
                    margin-bottom: 8px;
                    p{
                      color: $color-primary;
                      word-break: break-all;
                      text-overflow: ellipsis;
                      overflow: hidden;
                      display: -webkit-box;
                      -webkit-line-clamp: 2;
                      -webkit-box-orient: vertical;
                      .task-card-tit{
                        color: #666666;
                      }
                    }
                    .el-dropdown{
                      line-height: 15px;
                      display: inline;
                      cursor: pointer;
                      
                    }
                    span{
                        color: $color-primary;
                        font-size: 12px;  
                      }
                    
                }
                .task-card-li{
                    display: flex;
                    justify-content: flex-start;
                    p{
                        min-width: 86px;
                        margin-right: 12px;
                        .task_type{
                            color: #333333;
                        }
                        .task_see{
                            color: $color-primary;
                            cursor: pointer;
                        }

                    }
                }
            }
        }
    }
    .task-card-opearte{
        height: 32px;
        border-top: 1px solid#F5F5F5;
        & > div {
            cursor: pointer;
            flex: 1;
            text-align: center;
            line-height: 32px;            
            i{
                font-size: 12px;
                color: #999999;  
                &:hover{
                    color: $color-primary; 
                }
                &::before{
                    margin-right: 8px;
                }
            }
           
        }
        .task-card-opearte-more{
           border-right: 1px solid#F5F5F5;
           font-size: 14px;  
           &:hover{
               .el-dropdown{
                   color: $color-primary; 
               }
            }

        }
    }
}

.pointer{
    cursor: pointer;
}
.el-dropdown-menu{
    .opearte_btn{  
      font-size: 13px; 
      .iconfont{
          font-size: 14px;
          margin-right: 10px;
      } 
        .el-dropdown-menu__item{
            line-height: 30px;
        }  
    }

}
@media screen and (max-width: 1920px) {
  .task-card {
    width: calc(25% - 12px);
  }
  .task-card-name{
    width: 240px;
  }
  .task-card-des {
    width: 240px;
  }
}
@media screen and (max-width: 1680px) {
  .task-card {
    width: calc(33.3% - 12px);
  }
  .task-card-name{
    width: 200px;
  }
  .task-card-des {
    width: 200px;
  }
}
@media screen and (max-width: 1440px) {
  .task-card {
    width: 328px;
  }
  .task-card-name{
    width: 180px;
  }
  .task-card-des {
    width: 180px;
  }
}
@media screen and (max-width: 900px) {
  .task-card {
    width: calc(100% - 12px);
  }
  .task-card-name{
    width: 100px;
  }
  .task-card-des {
    width: 100px;
  }
}
</style>